<template>
  <div class="search">
    <form class="van-search" action="/">
      <van-search
        v-model="searchText"
        show-action
        placeholder="请输入搜索关键词"
        background="#3296fa"
        @search="onSearch"
        @cancel="onCancel"
        @focus="isResltShow = false"
      />
    </form>
    <!-- 模板控制方式1-标准写法 -->
    <!-- <search-result v-if="isResultShow"></search-result>
  <div v-else>
    <search-suggestion v-if="searchText"></search-suggestion>
    <search-history v-else></search-history>
  </div> -->
    <!-- 模板控制方式2-用template优化 -->
    <!-- <search-result v-if="isResultShow"></search-result>
  <template v-else>
    <search-suggestion v-if="searchText"></search-suggestion>
    <search-history v-else></search-history>
  </template> -->
    <!-- 最后进化为v-if v-else-if v-else -->
    <search-result v-if="isResltShow" :search-text="searchText"></search-result>
    <search-suggestion
      v-else-if="searchText"
      :searchText="searchText"
      @search="onSearch"
    ></search-suggestion>
    <search-history
      v-else
      :search-histories="searchHistories"
      @clear-search-histories="searchHistories = []"
      @search="onSearch"
    ></search-history>
  </div>
</template>

<script>
import SearchHistory from './components/search-history.vue'
import SearchSuggestion from './components/search-suggestion.vue'
import SearchResult from './components/search-result.vue'
import { getItem, setItem } from '@/utils/storage'
export default {
  name: 'SearchIndex',
  props: [],
  components: {
    SearchHistory,
    SearchSuggestion,
    SearchResult
  },
  data () {
    return {
      searchText: '',
      isResltShow: false,
      searchHistories: getItem('TOUTIAO-SEARCH-HISTORIES') || []
    }
  },
  created () {},
  mounted () {},
  methods: {
    onSearch (val) {
      this.searchText = val
      // 数组去重1-splice
      const index = this.searchHistories.findIndex(v => v === val)
      if (index > -1) {
        this.searchHistories.splice(index, 1)
      }
      this.searchHistories.unshift(val)
      // const set = new Set(this.searchHistories)
      // set.delete(val)
      // this.searchHistories = [val, ...set]
      this.isResltShow = true
    },
    onCancel () {
      this.$router.back()
    }
  },
  watch: {
    searchHistories (val) {
    // 同步到本地存储
      setItem('TOUTIAO-SEARCH-HISTORIES', val)
    }
  },
  computed: {}
}
</script>

<style lang="less" scoped>
.search {
  padding-top: 106px;
  .van-search {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    z-index: 1;
  }
  .van-search__action {
    color: #fff;
  }
}
</style>
